package net.zoneland.zrdp.framework.config;


import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * restTemplate配置.
 */
@Configuration(proxyBeanMethods = false)
@DependsOn("commonHttpClientPoolExecutor")
public class RestTemplateConfig {


    /**
     * 获取响应超时时间（单位为ms）。
     */
    private static final int READ_TIMEOUT = 6000;

    @Resource(name = "commonHttpClientPoolExecutor")
    private CloseableHttpClient commonHttpClientPoolExecutor;
    /**
     * rest工厂.
     * @return 请求工厂
     */
    @Bean
    public ClientHttpRequestFactory requestFactory() {

        final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(commonHttpClientPoolExecutor);
        // 设置读取超时时间（毫秒）
        factory.setReadTimeout(READ_TIMEOUT);
        return factory;
    }

    /**
     * rest模板.
     * @param requestFactory 请求工厂
     * @return rest模板
     */
    @Bean
    public RestTemplate restTemplate(final ClientHttpRequestFactory requestFactory) {
        // 添加转换器
        final List<HttpMessageConverter<?>> messageConverters = Arrays.asList(
            new StringHttpMessageConverter(StandardCharsets.UTF_8),
            new FormHttpMessageConverter(),
            new MappingJackson2HttpMessageConverter()
            );
        final RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    }


}
